﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PardesiServices.WinControls;
using System.IO;
using System.Collections;
using System.Security.Cryptography;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Media;




namespace HashingDirectory
{
    public partial class FormDecrypt : Form
    {
        public static bool recurseCheckbox ;
        static ArrayList filesToAdd = new ArrayList();
        private int no_of_files = 0;
        private int finished_files = 0;
        public string textToWrite = "";
        private double progress = 0;
        public string whereToSaveEncrypted = "";


        public FormDecrypt()
        {
            InitializeComponent();
            checkRecurse.Checked = true;
            recurseCheckbox = checkRecurse.Checked;

            //clearing counters
            no_of_files = 0;
            finished_files = 0;

        }



        private void DecryptFile(string sInputFile, string key)
        {
            string sOutputFile = FormEncrypt.GetFolderDirectory(sInputFile) + @"\decrypted_" + FormEncrypt.GetFileName(sInputFile);

            sOutputFile.Replace("encrypted_", "");


            //Creating the filestream from where to read - ENCRYPTED FILE
            FileStream fsInput = new FileStream(sInputFile, FileMode.Open, FileAccess.Read);


            //Creating an empty file to where to write - DECRYPTED FILE
            FileStream fsOutput = new FileStream(sOutputFile, FileMode.Create, FileAccess.Write);


            //Create Asymetric lagorithm
            Rijndael alg = Rijndael.Create();

            //Passign the key and iv
            alg.Padding = PaddingMode.PKCS7;
            alg.Key = FormEncrypt.HashAString(key);


            string IVstring = SecurityAndPrivacy.giveIVstring();

            alg.IV = FormEncrypt.HashAString(IVstring);


            CryptoStream cDec = new CryptoStream(fsInput, alg.CreateDecryptor(), CryptoStreamMode.Read);


            StreamWriter swWriter = new StreamWriter(fsOutput);

            StreamReader sReader = new StreamReader(cDec);


            try
            {

                // Write out the decrypted stream.

                swWriter.Write(sReader.ReadToEnd());

            }

            catch (CryptographicException ex)
            {

                System.Diagnostics.Debug.WriteLine(ex.Message);

            }

            finally
            {

                // Close and clean up.

                swWriter.Close();

                cDec.Close();

            }


        }




        private void button1_Click(object sender, EventArgs e)
        {
            //Process Button

            no_of_files = checkedListBox1.Items.Count;

            //fill up the arraylist

            for (int a = 0; a < checkedListBox1.Items.Count; a++)
            {
                filesToAdd.Add(checkedListBox1.Items[a].ToString());
            }


            //Getting the key
            string sKey1 = txKey1.Text;
            string sKey2 = txKey2.Text;

            if (sKey1.Length < 2) 
            {
                MessageBox.Show("The key needs to be a minimum of 2 characters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string sSecretKey = null;

            //Comparing keys
            if (sKey1 != sKey2)
            {
                MessageBox.Show("The keys do NOT match", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            else
            {
                sSecretKey = sKey1;
            }


            //Inserting Hashes

            foreach (string fpath in filesToAdd)
            {


                DecryptFile(fpath, sSecretKey);
                finished_files++;
                label_processedfiles.Text = finished_files.ToString();
                progress = ((double)finished_files / (double)no_of_files ) * 100D;
                try
                {
                    toolStripProgressBar1.Value = Convert.ToInt32(progress);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }

            }


            //starting the wav vile

            Assembly asm = Assembly.GetExecutingAssembly();
            Stream sm = asm.GetManifestResourceStream("HashingDirectory.finish.wav");
            SoundPlayer sPlayer = new SoundPlayer(sm);
            sPlayer.Play();



            label4.Text = "Files Processed";

  

            MessageBox.Show("A Total of " + finished_files + " files were processed successfully", "Finished", MessageBoxButtons.OK, MessageBoxIcon.Information);



            //Removing the buttons
            
            exit_button.TabIndex = 0;

            btnOpenFolder.Visible = true;
            processButton.Enabled = false;




        }

        private void ProcessDirectory(string targetDirectory)
        {
            // Process the list of files found in the directory.
            string[] fileEntries = Directory.GetFiles(targetDirectory);
            foreach (string fileName in fileEntries)
                ProcessFile(fileName);


            if (recurseCheckbox == true)
            {

                // Recurse into subdirectories of this directory.
                string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
                foreach (string subdirectory in subdirectoryEntries)
                    ProcessDirectory(subdirectory);
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            //Browse Button

            FolderBrowser myBrowser = new FolderBrowser();
            myBrowser.Title = "Choose Directory to Encrypt";
            myBrowser.Flags = BrowseFlags.BIF_NEWDIALOGSTYLE |
                              BrowseFlags.BIF_STATUSTEXT |
                              BrowseFlags.BIF_EDITBOX; ;
            DialogResult res = myBrowser.ShowDialog();
            if (res == DialogResult.OK)
            {
                string myPath = myBrowser.DirectoryPath;
                textBox1.Text = myPath;
                ProcessDirectory(myPath);
                checkedListBox1.CheckOnClick = true;
                lbl_totalfiles.Text = no_of_files.ToString();              

            }

            //setting the folder where to save the csv
            whereToSaveEncrypted = myBrowser.DirectoryPath ;

            txt_SaveCSVPath.Text = whereToSaveEncrypted;


            //enablign process button
            processButton.Enabled = true;

        }

        private void checkRecurse_CheckedChanged(object sender, EventArgs e)
        {
            recurseCheckbox = checkRecurse.Checked;
        }

     
        private void button2_Click_1(object sender, EventArgs e)
        {
            //Clear the multiline box
            textBox1.Text = "";
            filesToAdd.Clear();
            checkedListBox1.Items.Clear();
            //clearing counters
            no_of_files = 0;
            finished_files = 0;
            processButton.Enabled = false;
            btnOpenFolder.Visible = false;
            lbl_totalfiles.Text = no_of_files.ToString();
            label_processedfiles.Text = finished_files.ToString();
            whereToSaveEncrypted = "";
            toolStripProgressBar1.Value = 0;

        }

        private void button3_Click(object sender, EventArgs e)
        {
            //Exit the Form
            this.Close();
        }


        
        private void checkedListBox1_ItemCheck_1(object sender, ItemCheckEventArgs e)
        {
            CheckState c = e.CurrentValue;

            switch (c)
            {
                case CheckState.Checked:
                        MessageBox.Show("The Selected File will NOT be Processed");
                        e.NewValue = CheckState.Unchecked;
                        no_of_files--;
                        lbl_totalfiles.Text = no_of_files.ToString();
                        break; ;
                case CheckState.Indeterminate:
                        MessageBox.Show("The Selected File will BE Processed");
                        e.NewValue = CheckState.Checked;
                        no_of_files++;
                        lbl_totalfiles.Text = no_of_files.ToString();
                        break;
                case CheckState.Unchecked:
                        //MessageBox.Show("The Selected File will BE Processed"); 
                        e.NewValue = CheckState.Checked;
                        no_of_files++;
                        lbl_totalfiles.Text = no_of_files.ToString();
                        break;
            }
            

        }

        private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            string p = FormEncrypt.GetFolderDirectory(whereToSaveEncrypted) + @"\GeneratedHashes.csv";
            System.Diagnostics.Process.Start(p);
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AboutBox1 AboutMe = new AboutBox1();
            AboutMe.Show();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(FormEncrypt.GetFolderDirectory(whereToSaveEncrypted));
        }

        private void ProcessFile(string path)
        {
            //filesToAdd.Add (path);
            checkedListBox1.Items.Add(path, true);
            //no_of_files++;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            //file open

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Hash Files";
            ofd.AddExtension = true;
            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;
            ofd.Multiselect = true;


            ofd.ShowDialog();

            foreach (string fajl in ofd.FileNames)
            {
                string thisFpath = fajl;
                textBox1.Text = FormEncrypt.GetFolderDirectory(thisFpath);
                no_of_files++;
                //enablign process button
                processButton.Enabled = true;
                ProcessFile(thisFpath);

            }

            lbl_totalfiles.Text = no_of_files.ToString();

            //setting the folder where to save the csv
            whereToSaveEncrypted = textBox1.Text + @"\GeneratedHashes.csv";

            txt_SaveCSVPath.Text = whereToSaveEncrypted;
        }

        private void textBox1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void textBox1_DragDrop(object sender, DragEventArgs e)
        {
            string[] FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);

            foreach (string File in FileList)
            {
                textBox1.Text = FormEncrypt.GetFolderDirectory(File);
                ProcessFile(File);
                no_of_files++;
            }

            
            lbl_totalfiles.Text = no_of_files.ToString();
            //enablign process button
            processButton.Enabled = true;
            //ProcessFile(s);
        }

        private void button3_Click_2(object sender, EventArgs e)
        {
            FolderBrowser sBrowser = new FolderBrowser();
            sBrowser.Title = "Choose Where to Save The CSV";
            sBrowser.Flags = BrowseFlags.BIF_NEWDIALOGSTYLE |
                              BrowseFlags.BIF_STATUSTEXT |
                              BrowseFlags.BIF_EDITBOX; ;

            DialogResult res = sBrowser.ShowDialog();
            if (res == DialogResult.OK)
            {
                whereToSaveEncrypted = sBrowser.DirectoryPath + @"\GeneratedHashes.csv";

                txt_SaveCSVPath.Text = whereToSaveEncrypted;

            }
        }
        

    }
}
